define([
  'underscore',
  'collections/Contents',
  'models/AlertMessage',
  'models/Message',
  'views/View',
  'views/Modal',
  'views/users/UploadedView',
  'views/users/UploadView',
  'views/users/UsersSelection',
  'hbs!template/users/share',
  'hbs!template/users/share-actions',  
  'hbs!template/users/success-modal',
  'hbs!template/users/error-modal'
], function( _, Contents, AlertMessage, Message, View, Modal, UploadedView, UploadView, UsersSelection, template, actionsTemplate, successTemplate, errorTemplate){
  var ActionsView = View.extend({
    template: actionsTemplate,

    initialize: function(options) {
      options || (options = {});
      if(options.enable) {
        this.enable = true;
      } else {
        this.enable = false;
      }
    },

    getRenderData: function() {
      var data = View.prototype.getRenderData.call(this);
      data._enable = this.enable;
      return data;
    }
      
  });
  
  var ShareView = View.extend({
    template: template,

    events: {
      "click button[name=old]":         "uploaded",
      "click button[name=new]":         "uploadFiles",
      "click button[name=owned]":       "ownedFn",
      "click button[name=share]":       "share",
      "click button[name=cancel]":      "back"
    },

    initialize: function(options) {
      options || (options = {});
      View.prototype.initialize.call(this, options);

      if(options.text) {
        this.text = options.text;
        this.onlyText = true;
      } 
      this.upload = false; // Flag to know which area is selected, uploaded or upload files.
      this.owned = true;  // Flag to know if the content showed in the uploaded is owned or shared. (Now it's only for internal users.)
      // View and collection for uploaded photos.
      
      // View for upload new photos

      _.bind(this.sendMessage, this);
      this.model.bind("change", this.render, this);
      this.options = options;
    },

    ownedFn: function() {
      this.owned = false;
      this.render();
    },
    
    uploaded: function() {
      this.upload = false;
      this.owned = true;
      this.render();
      //this.renderUploaded();
    },

    uploadFiles: function() {
      this.upload = true;
      this.render();
      //this.renderUpload();
    },

    render: function() {
      View.prototype.render.call(this);
      var userCollection;
      if(this.options.type === "familiar" || this.options.type == "admin") {
        userCollection = this.model.internals;
      } else {
        userCollection = this.model.familiars;
      }
      this.usersSelectionView = new UsersSelection({el: this.$("#users-selection"), collection: userCollection, type: this.options.type});        
 
      // View for users selection
      this.usersSelectionView.render();
      userCollection.fetch();
      this.usersSelectionView.bind("update:selection", this.renderActions, this); // Binding to enable share action
      
      if(this.upload) {
        this.uploadView = new UploadView({el: this.$("#media-files")});
        this.uploadView.render();

        this.uploadView.initBox();
      } else {
        var uploadedPhotos = new Contents([], {type: "photo", owned: this.owned});
        uploadedPhotos.pagination.setLimit(5);
        this.uploadedView = new UploadedView({el: this.$("#media-files"), collection: uploadedPhotos});
        this.uploadedView.render();
        
        uploadedPhotos.fetch();
        
      }
      this.renderActions();
      return this;
    },

    renderActions: function() {
      var enable = false;
      if(this.usersSelectionView && this.usersSelectionView.getReceivers() && this.usersSelectionView.getReceivers().length > 0) {
        enable = true;
      }
      this.actionsView = new ActionsView({el: this.$("#share-buttons"), enable: enable});
      this.actionsView.render();
    },
    
    share: function() {
      // Avoid multiple clicks
      if(this.$("#shareButton").hasClass("disabled")) {
          return;
      } else { // First click.
        this.Logger.debug("ShareView-> share action!");
        this.$("#shareButton").addClass("disabled");
        
        var contents = new Contents(),
        tmp = [], // Temporal array where the contents will be pushed after be uploaded.
        that = this,
        count; // Counter for knowing how many files have to be uploaded. 
        
        contents.bind("reset", function(){
          that.sendMessage(this);
        });

        // If the user is uploading. Set a callback to get the generated content and put it into the tmp array.
        if(this.upload) {
          count = this.uploadView.getFiles().length || 0; 
          this.uploadView.upload(function(id, source){
            tmp.push({id: id, type: "photo" , source: source});
            var $progress = that.$("#progress_upload", this.el);
            var value = (tmp.length / count) * 100;
            $progress.width(value + "%");
            if(tmp.length === count) { // Reset the contents collection to fire the reset event.
              contents.reset(tmp);
            } else {
            }
          });
          
        } else {
          // If the the users has selected the content (because it was uploaded before). Just get it through the corresponding view.
          var selected = this.uploadedView.getSelected();
          _.each(selected, function(element){          
            tmp.push({id: element.id, type: "photo", source: element.get("original").source});
          });
          contents.reset(tmp);
        }
      }

    },

    sendMessage: function(contents) {
      var body = this.$("#body_message", this.el).val();
      var receivers = this.usersSelectionView.getReceivers();
      var message = new Message({
        receivers: receivers,
        contents: contents.models,
        body: body
      });

      message.bind("success_save", this.successHandler, this);
      message.bind("error_save", this.errorHandler, this);
      
      console.log("-------------- Enviando mensaje -----------------");
      console.log(message);
      console.log("-----------------------------------------------");
      message.save();
    },

    successHandler: function(model, response) {
      this.$("#shareButton").removeClass("disabled");
      this.initialize(this.options);
      
      var successModal = new Modal({template: successTemplate});
      successModal.render();
      
      this.render();
    },

    errorHandler: function(model, response) {
      this.initialize(this.options);
      
      var errorModal = new Modal({template: errorTemplate});
      errorModal.render();
      
      this.render();
    },

    getRenderData: function() {
      var data = View.prototype.getRenderData.call(this);
      data._upload = this.upload;
      data._internal = this.options.type === "internal";
      data._owned = this.owned;

      if(this.options.url) {
        data.message = this.options.url;
      }
      return data;
    }

  });

  return ShareView;
});